<!--  -->
<template>
  <div>
    <!-- 面包屑区域 -->
    <el-breadcrumb separator-class="el-icon-arrow-right">
      <el-breadcrumb-item :to="{ path: '/home' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>商品管理</el-breadcrumb-item>
      <el-breadcrumb-item>商品分类</el-breadcrumb-item>
    </el-breadcrumb>
    <!-- 卡片区域 -->
    <el-card>
      <!-- 添加分类 -->
      <el-row :gutter="30">
        <el-col :span="6" class="btn">
          <el-button type="primary" @click="showAddCateDialog"
            >添加分类</el-button
          >
        </el-col>
      </el-row>
      <!-- 表格区域 -->
      <el-table
        :data="categoriesList"
        border
        row-key="cat_id"
        :tree-props="{ children: 'children' }"
      >
        <!-- 索引列 -->
        <!-- <el-table-column type="index" label="#"></el-table-column> -->
        <el-table-column prop="cat_name" label="分类名称"></el-table-column>
        <el-table-column prop="" label="是否有效">
          <template slot-scope="scope">
            <i v-if="!scope.row.cat_deleted" class="el-icon-success"></i>
            <i v-else class="el-icon-error"></i>
          </template>
        </el-table-column>
        <!-- 排序 -->
        <el-table-column prop="cat_level" label="排序">
          <template slot-scope="scope">
            <el-tag v-if="scope.row.cat_level === 0">一级</el-tag>
            <el-tag type="success" v-else-if="scope.row.cat_level === 1"
              >二级</el-tag
            >
            <el-tag type="warning" v-else>三级</el-tag>
          </template>
        </el-table-column>
        <!-- 操作 -->
        <el-table-column prop="" label="操作">
          <template slot-scope="scope">
            <el-button
              type="primary"
              icon="el-icon-edit"
              size="small"
              @click="showEditCateDialog(scope.row)"
              >编辑</el-button
            >
            <el-button
              type="danger"
              icon="el-icon-delete"
              size="small"
              @click="deletCategory(scope.row)"
            >
              删除</el-button
            >
          </template>
        </el-table-column>
      </el-table>
      <!-- 页码区域 -->
      <div>
        <el-pagination
          @size-change="cateHandleSizeChange"
          @current-change="cateHandleCurrentChange"
          :current-page="queryInfo.pagenum"
          :page-sizes="[5, 10, 30, 50]"
          :page-size="queryInfo.pagesize"
          layout="total, sizes, prev, pager, next, jumper"
          :total="total"
        >
        </el-pagination>
      </div>
      <!-- 添加分类dialog -->
      <el-dialog
        title="添加分类"
        :visible.sync="addCategorysVisible"
        width="35%"
        @close="addCateDialogClose"
      >
        <el-form
          :model="addCateRuleForm"
          :rules="addCateRules"
          ref="addCateRef"
          label-width="100px"
        >
          <el-form-item label="分类名称" prop="cat_name">
            <el-input v-model="addCateRuleForm.cat_name"></el-input>
          </el-form-item>

          <el-form-item label="父级分类">
            <el-cascader
              v-model="selectedKeys"
              :options="parentCateList"
              :props="{
                expandTrigger: 'hover',
                ...cascaderProps,
                checkStrictly: true,
              }"
              @change="parentCateChanged"
              clearable
            ></el-cascader>
          </el-form-item>
        </el-form>

        <span slot="footer" class="dialog-footer">
          <el-button @click="addCategorysVisible = false">取 消</el-button>
          <el-button type="primary" @click="addCategorys">确 定</el-button>
        </span>
      </el-dialog>
      <!-- 编辑dialog -->
      <el-dialog title="编辑" :visible.sync="editCategorysVisible" width="50%">
        <el-form
          :model="editCateForm"
          :rules="addCateRules"
          ref="editCateRef"
          label-width="100px"
        >
          <el-form-item label="活动名称" prop="cat_name">
            <el-input v-model="editCateForm.cat_name"></el-input>
          </el-form-item>
        </el-form>
        <span slot="footer" class="dialog-footer">
          <el-button @click="editCategorysVisible = false">取 消</el-button>
          <el-button type="primary" @click="editCategories">确 定</el-button>
        </span>
      </el-dialog>
    </el-card>
  </div>
</template>

<script>
export default {
  data() {
    return {
      addCategorysVisible: false,
      editCategorysVisible: false,
      // 获取分类列表的参数
      queryInfo: {
        type: 3,
        pagenum: 1,
        pagesize: 5,
      },
      categoriesList: [],
      // 总数居条数
      total: 0,
      // 添加分类相关
      addCateRuleForm: {
        cat_pid: 0,
        cat_name: '',
        cat_level: 0,
      },
      addCateRules: {
        cat_name: [
          { required: true, message: '请输入分类名称' },
          { min: 2, max: 8, message: '长度在 2 到 15 个字符', trigger: 'blur' },
        ],
      },
      // 父级分类选项
      parentCateList: [],
      // selectedKeys保存props属性中的value值，此处是cat_id
      selectedKeys: [],
      cascaderProps: {
        value: 'cat_id',
        label: 'cat_name',
        children: 'children',
      },
      // 编辑分类
      editCateForm: {
        cat_name: '',
      },
      editCateId: 0,
    }
  },
  created() {
    this.getCategoriesList()
  },
  methods: {
    // 获取分类列表
    async getCategoriesList() {
      const { data: res } = await this.$http.get('categories', {
        params: this.queryInfo,
      })
      // console.log(res)
      if (res.meta.status !== 200) {
        return this.$message.error('获取分类列表失败！')
      }
      this.categoriesList = res.data.result
      this.total = res.data.total
    },
    // 根据底部页码大小显示数据条数
    cateHandleSizeChange(val) {
      this.queryInfo.pagesize = val
      this.getCategoriesList()
    },
    // 跳转页码
    cateHandleCurrentChange(val) {
      this.queryInfo.pagenum = val
      this.getCategoriesList()
    },
    // 展示addCateDialog
    async showAddCateDialog() {
      this.addCategorysVisible = true
      const { data: res } = await this.$http.get('categories', {
        params: { type: 2 },
      })
      if (res.meta.status !== 200) {
        return this.$message.error('获取分类列表失败！')
      }
      this.parentCateList = res.data
    },
    // 关闭addCateDialog时重置表单信息
    addCateDialogClose() {
      this.$refs.addCateRef.resetFields()
      this.selectedKeys = []
      this.addCateRuleForm.cat_pid = 0
      this.addCateRuleForm.cat_level = 0
    },
    //选择项发生时变化触发
    parentCateChanged() {
      console.log(this.selectedKeys)
      // 如果selectedKeys数组长度大于0，则证明选择了父级分类，否则则添加一级分类
      if (this.selectedKeys.length !== 0) {
        this.addCateRuleForm.cat_pid =
          this.selectedKeys[this.selectedKeys.length - 1]
        this.addCateRuleForm.cat_level = this.selectedKeys.length
        return
      } else {
        this.addCateRuleForm.cat_pid = 0
        this.addCateRuleForm.cat_level = 0
      }
    },
    // 添加分类
    addCategorys() {
      this.$refs.addCateRef.validate(async (val) => {
        if (!val) return
        else {
          const { data: res } = await this.$http.post(
            'categories',
            this.addCateRuleForm
          )
          if (res.meta.status !== 201) {
            return this.$message.error('创建失败！')
          }
          this.$message.success(res.meta.msg)
          this.addCategorysVisible = false
          this.getCategoriesList()
        }
      })
    },
    // 展示编辑分类
    async showEditCateDialog(info) {
      this.editCateId = info.cat_id
      this.editCategorysVisible = true
      const { data: res } = await this.$http.get(`categories/${info.cat_id}`)
      if (res.meta.status !== 200) {
        return this.$message.error('获取分类信息失败！')
      }
      this.editCateForm.cat_name = info.cat_name
    },
    // 编辑分类
    editCategories() {
      this.$refs.editCateRef.validate(async (val) => {
        if (!val) return
        else {
          const { data: res } = await this.$http.put(
            `categories/${this.editCateId}`,
            this.editCateForm
          )
          if (res.meta.status !== 200) {
            return this.$message.error(res.meta.msg)
          }
          this.getCategoriesList()
          this.editCategorysVisible = false
          this.$message.success(res.meta.msg)
        }
      })
    },
    // 删除分类
    deletCategory(info) {
      this.$confirm(`此操作将永久删除${info.cat_name}分类, 是否继续?`, '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning',
      })
        .then(async () => {
          const { data: res } = await this.$http.delete(
            `categories/${info.cat_id}`
          )
          this.getCategoriesList()
          this.$message.success(res.meta.msg)
        })
        .catch(() => {
          this.$message.info('已取消删除')
        })
    },
  },
}
</script>

<style scoped>
.btn {
  float: right;
}
.el-icon-success {
  color: #279ea0;
}
.el-icon-error {
  color: red;
}
.el-cascader {
  width: 100%;
}
</style>
